#include "QHttpClient.h"

namespace QtNet {

QThreadStorage<QNetworkAccessManager*> QHttpClient::threadStorage;

QNetworkAccessManager *QHttpClient::getNetworkAccessManager()
{
    if (!threadStorage.hasLocalData())
        threadStorage.setLocalData(new QNetworkAccessManager);
    return threadStorage.localData();
}

void QHttpClient::handleException(const nlohmann::json::exception &e, const QString &_type)
{
    QString type = _type;
    qDebug() << "----------------------------异常分析----------------------------";
    qDebug() << "id: " << e.id;

    if (!type.isEmpty()) {
        if (type.size() > 1)
            qDebug() << "类型:" << type.remove(0, 1);
        else
            qDebug() << "类型:" << type;
    }

    qDebug() << "消息:" << QString::fromStdString(std::string(e.what()));
    if (dynamic_cast<const json::parse_error*>(&e)) {
        qDebug() << "异常类型: parse_error (解析错误)";
        const auto* parse_err = dynamic_cast<const json::parse_error*>(&e);
        qDebug() << "字节位置: " << parse_err->byte;
    } else if (dynamic_cast<const json::type_error*>(&e)) {
        qDebug() << "异常类型: type_error (类型错误)";
    } else if (dynamic_cast<const json::out_of_range*>(&e)) {
        qDebug() << "异常类型: out_of_range (越界访问)";
    } else if (dynamic_cast<const json::invalid_iterator*>(&e)) {
        qDebug() << "异常类型: invalid_iterator (无效迭代器)";
    } else if (dynamic_cast<const json::other_error*>(&e)) {
        qDebug() << "异常类型: other_error (其他错误)";
    } else {
        qDebug() << "异常类型: 未知的JSON异常";
    }
}

}
